package com.yuntu.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.yuntu.annotation.AuthCheck;
import com.yuntu.annotation.SaSpaceCheckPermission;
import com.yuntu.api.aliyunai.AliYunAiApi;
import com.yuntu.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.yuntu.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.yuntu.api.imageSearch.ImageSearchApiFacade;
import com.yuntu.api.imageSearch.model.ImageSearchResult;
import com.yuntu.common.BaseResponse;
import com.yuntu.common.DeleteRequest;
import com.yuntu.common.ResultUtils;
import com.yuntu.demo.constant.UserConstant;
import com.yuntu.demo.dto.picture.*;
import com.yuntu.demo.entity.Picture;
import com.yuntu.demo.entity.PictureTagCategory;
import com.yuntu.demo.entity.Space;
import com.yuntu.demo.entity.User;
import com.yuntu.demo.enums.PictureReviewStatusEnum;
import com.yuntu.demo.vo.LoginUserVO;
import com.yuntu.demo.vo.PictureVO;
import com.yuntu.exception.ErrorCode;
import com.yuntu.exception.ThrowUtils;
import com.yuntu.exception.bizException;
import com.yuntu.manager.auth.SpaceUserAuthManager;
import com.yuntu.manager.auth.StpKit;
import com.yuntu.manager.auth.model.SpaceUserPermissionConstant;
import com.yuntu.service.ISpaceService;
import com.yuntu.service.IUserService;
import com.yuntu.service.impl.PictureServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 图片 前端控制器
 * </p>
 *
 * @author k
 * @since 2025-03-20
 */
@RestController
@RequestMapping("/picture")
@Api("图片相关接口")
public class PictureController {
    @Autowired
    IUserService userService;
    @Autowired
    PictureServiceImpl pictureService;
    @Resource
    StringRedisTemplate stringRedisTemplate;//分布缓存
    @Resource
    Cache<String, Object> caffeineCache;//本地缓存
    @Resource
    ISpaceService spaceService;
    @Resource
    AliYunAiApi aliYunAiApi;
    @Autowired
    private SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 上传图片（可重新上传）
     */
    @PostMapping("/upload")
    @ApiOperation("上传文件")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPicture(
            @RequestPart("file") MultipartFile multipartFile,
            PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        LoginUserVO loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }
    /**
     * 通过 URL 上传图片（可重新上传）
     */
    @PostMapping("/upload/url")
    @ApiOperation("通过 URL 上传图片")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        LoginUserVO loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    @PostMapping("delete")
    @ApiOperation("删除图片")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest,
                                               HttpServletRequest request) {
        //判断是否存在
        if(deleteRequest.getId()==null){
            throw new bizException(ErrorCode.PARAMS_ERROR);
        }
        LoginUserVO loginUser = userService.getLoginUser(request);
        pictureService.deletePicture(deleteRequest.getId(), loginUser);
        return ResultUtils.success(true);
    }
    @PostMapping("update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("管理员修改图片")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest,
                                               HttpServletRequest request) {
        //先判断是否有该图片
        if(pictureUpdateRequest.getId()==null){
            throw new bizException(ErrorCode.PARAMS_ERROR);
        }
        //查出数据
        Picture oldPicture = pictureService.lambdaQuery().eq(Picture::getId, pictureUpdateRequest.getId()).one();
        if(oldPicture==null){
            throw new bizException(-1,"没有这张图片");
        }
        Picture picture=new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest,picture);
        //将传来的tags转换为json
        String tags = JSONUtil.toJsonStr(pictureUpdateRequest.getTags());
        picture.setTags(tags);
        //填充审核信息
        LoginUserVO loginUser = userService.getLoginUser(request);
        pictureService.fillReviewParams(picture,loginUser);
        //修改数据库
        boolean update = pictureService.updateById(picture);
        ThrowUtils.throwIf(!update,ErrorCode.SYSTEM_ERROR);
        return ResultUtils.success(true);
    }
    @GetMapping("get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("管理员根据Id查图片")
    public BaseResponse<Picture> getPictureById(Long id,HttpServletRequest request) {
        ThrowUtils.throwIf(id == null,ErrorCode.PARAMS_ERROR);
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture==null,new bizException(-1,"没有这张图片"));
        return ResultUtils.success(picture);
    }
    @GetMapping("get/vo")
    @ApiOperation("查图片vo")
    public BaseResponse<PictureVO> getPictureVoById(Long id,HttpServletRequest request) {
        ThrowUtils.throwIf(id == null,ErrorCode.PARAMS_ERROR);
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture==null,new bizException(-1,"没有这张图片"));
        LoginUserVO loginUser = userService.getLoginUser(request);
        //看查的是否是公共空间，如果不是，只有空间管理员可以查看
        Space space=new Space();
        if(picture.getSpaceId()!=null){
//            pictureService.checkPictureAuth(loginUser,picture);
            //改成用编程式权限校验
            boolean hasmission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasmission,ErrorCode.NO_AUTH_ERROR);
            space=spaceService.getById(picture.getSpaceId());
            ThrowUtils.throwIf(space==null,ErrorCode.NOT_FOUND_ERROR,"空间不存在");
        }
        //查询审核状态（审核通过的才返回）,但是自己应该可以访问到自己的所有图片
//        if (!loginUser.getId().equals(picture.getUserId())&&!picture.getReviewStatus().equals(PictureReviewStatusEnum.PASS.getValue())) {
//            return null;
//        }
//        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq(Picture::getReviewStatus,PictureReviewStatusEnum.PASS.getValue());
        PictureVO pictureVO = pictureService.getPictureVO(picture, request);
        //获取权限列表
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        pictureVO.setPermissionList(permissionList);
        return ResultUtils.success(pictureVO);
    }
    @PostMapping("list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("管理员分页查询所有图片")
    public BaseResponse<Page<Picture>> getPicturePage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = pictureService.getQueryWrapper(pictureQueryRequest);
        Long current = (long) pictureQueryRequest.getCurrent();
        Long pageSize = (long) pictureQueryRequest.getPageSize();
        Page<Picture> page = pictureService.page(new Page<Picture>(current, pageSize), queryWrapper);
        return ResultUtils.success(page);
    }
    @PostMapping("list/page/vo")
    @ApiOperation("分页查询图片")
    public BaseResponse<Page<PictureVO>> getPictureVoPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                        HttpServletRequest request) {
        LoginUserVO loginUser = userService.getLoginUser(request);
        Long spaceId = pictureQueryRequest.getSpaceId();
        //判断是查公共空间还是私人空间
        if(spaceId!=null){
            //私人空间，校验权限
            //看该私人空间管理员是否是登录者
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space==null,ErrorCode.PARAMS_ERROR,"没有该空间");
//            if(!space.getUserId().equals(loginUser.getId())){
//                throw new bizException(ErrorCode.NO_AUTH_ERROR);
//            }
            //改成用编程式权限校验
            boolean hasmission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasmission,ErrorCode.NO_AUTH_ERROR);
            pictureQueryRequest.setNullSpaceId(false);
        }else{
            //查公共空间
            pictureQueryRequest.setNullSpaceId(true);
        }
        QueryWrapper<Picture> queryWrapper = pictureService.getQueryWrapper(pictureQueryRequest);
        Long current = (long) pictureQueryRequest.getCurrent();
        Long pageSize = (long) pictureQueryRequest.getPageSize();
        //防止爬虫
        ThrowUtils.throwIf(pageSize>30,ErrorCode.PARAMS_ERROR);
        //加入多级缓存-》先查本地缓存-》没有-》再查分布缓存-》没有-》查数据库
        //先生成查询的键
        String jsonStr = JSONUtil.toJsonStr(pictureQueryRequest);
        //由于json过长，通过md5将其压缩
        String hashKey = DigestUtils.md5DigestAsHex(jsonStr.getBytes());
        //得到存储的key
        String chaKey="yuntu:listPageVo"+hashKey;
        //先查本地缓存
//        String cacheValue = (String) caffeineCache.getIfPresent(chaKey);
//        if(cacheValue!=null){
//            //将json转换为bean
//            Page<PictureVO> bean = JSONUtil.toBean(cacheValue, Page.class);
//            return ResultUtils.success(bean);
//        }
//        //本地缓存为空，查redis
//        cacheValue= stringRedisTemplate.opsForValue().get(chaKey);
//        if(cacheValue!=null){
//            //将json转换为bean
//            Page<PictureVO> bean = JSONUtil.toBean(cacheValue, Page.class);
//            return ResultUtils.success(bean);
//        }
        //缓存都没有，查数据库
        //加入审核条件
        if(spaceId==null){
            queryWrapper.eq("reviewStatus", PictureReviewStatusEnum.PASS.getValue());
        }
        Page<Picture> page = pictureService.page(new Page<Picture>(current, pageSize), queryWrapper);
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(page, request);
        //将得到的数据转json存入数据库
        String pictureVOPageJson = JSONUtil.toJsonStr(pictureVOPage);
        //存redis
        //设置有效时间-》5到10分钟-》避免缓存雪崩
        //在自己项目，为了测试，设置30到60秒
//        long timeOut=30+ RandomUtil.randomInt(30);
//        stringRedisTemplate.opsForValue().set(chaKey,pictureVOPageJson,timeOut, TimeUnit.SECONDS);
//        //存本地缓存
//        caffeineCache.put(chaKey,pictureVOPageJson);
        return ResultUtils.success(pictureVOPage);
    }
    @PostMapping("edit")
    @ApiOperation("编辑图片")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest,
                                             HttpServletRequest request) {
        LoginUserVO loginUser = userService.getLoginUser(request);
        pictureService.editPicture(pictureEditRequest,loginUser);
        return ResultUtils.success(true);
    }
    @GetMapping("/tag_category")
    @ApiOperation("获取类别")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList(
                "热门", "搞笑", "生活", "高清", "艺术",
                "校园", "背景", "简历", "创意", "实用",
                "简约", "复古", "科技", "商务", "儿童",
                "节日", "美食", "旅行", "运动", "自然"
        );
        List<String> categoryList = Arrays.asList(
                "模板", "电商", "表情包", "素材", "海报",
                "插画", "图标","壁纸","头像"
        );
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("审核")
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest,
                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        LoginUserVO loginUser = userService.getLoginUser(request);
        User user=new User();
        BeanUtils.copyProperties(loginUser,user);
        pictureService.doPictureReview(pictureReviewRequest, user);
        return ResultUtils.success(true);
    }
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("批量爬取图片")
    public BaseResponse<Integer> uploadPictureByBatch(
            @RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
            HttpServletRequest request
    ) {
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        LoginUserVO loginUser = userService.getLoginUser(request);
        int uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(uploadCount);
    }
    /**
     * 以图搜图
     */
    @PostMapping("/search/picture")
    @ApiOperation("以图搜图")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        Picture oldPicture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        List<ImageSearchResult> resultList = ImageSearchApiFacade.searchImage(oldPicture.getThumbnailUrl());
        return ResultUtils.success(resultList);
    }
    @PostMapping("/search/color")
    @ApiOperation("以颜色搜索")
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest,
                                                              HttpServletRequest request) {
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(searchPictureByColorRequest.getPicColor() == null, ErrorCode.PARAMS_ERROR,"未传入需要的颜色");
        String picColor = searchPictureByColorRequest.getPicColor();
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        LoginUserVO loginUser = userService.getLoginUser(request);
        List<PictureVO> pictureVOS = pictureService.searchPictureByColor(spaceId, picColor, loginUser);
        return ResultUtils.success(pictureVOS);
    }
    @PostMapping("edit/batch")
    @ApiOperation("批量编辑图片")
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest,
                                                    HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        LoginUserVO loginUser = userService.getLoginUser(request);
        pictureService.editPictureByBatch(pictureEditByBatchRequest,loginUser);
        return ResultUtils.success(true);
    }
    /**
     * 创建 AI 扩图任务
     */
    @PostMapping("/out_painting/create_task")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(
            @RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest,
            HttpServletRequest request) {
        if (createPictureOutPaintingTaskRequest == null || createPictureOutPaintingTaskRequest.getPictureId() == null) {
            throw new bizException(ErrorCode.PARAMS_ERROR);
        }
        LoginUserVO loginUser = userService.getLoginUser(request);
        CreateOutPaintingTaskResponse response = pictureService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * 查询 AI 扩图任务
     */
    @GetMapping("/out_painting/get_task")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetOutPaintingTaskResponse task = aliYunAiApi.getOutPaintingTask(taskId);
        return ResultUtils.success(task);
    }

}
